package com.qixin.modules.eaApplication.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.qixin.modules.eaApplication.service.IEaBusinessApplyChangeService;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.nc.entity.NcPersonnel;
import org.jeecg.modules.nc.service.INcPersonnelService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import com.qixin.modules.eaApplication.entity.EaBusinessPerDtl;
import com.qixin.modules.eaApplication.entity.EaBusinessApplyChange;
import com.qixin.modules.eaApplication.vo.EaBusinessApplyChangePage;
import com.qixin.modules.eaApplication.service.IEaBusinessApplyChangeServiceCopy;
import com.qixin.modules.eaApplication.service.IEaBusinessPerDtlService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: ea_business_apply_change
 * @Author: qixin-boot
 * @Date:   2022-01-21
 * @Version: V1.0
 */
@Api(tags="出差申请变更单")
@RestController
@RequestMapping("/eaApplication/eaBusinessApplyChange")
@Slf4j
public class EaBusinessApplyChangeController {
	@Autowired
	private IEaBusinessApplyChangeService eaBusinessApplyChangeService;
	@Autowired
	private IEaBusinessPerDtlService eaBusinessPerDtlService;
	@Autowired
	private INcPersonnelService ncPersonnelService;
	
	/**
	 * 分页列表查询
	 *
	 * @param eaBusinessApplyChange
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="出差申请变更单-分页列表查询", notes="出差申请变更单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(EaBusinessApplyChange eaBusinessApplyChange,
								   @RequestParam(name="billDateBegin", required = false) String billDateBegin,
								   @RequestParam(name="billDateEnd", required = false) String billDateEnd,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<EaBusinessApplyChange> queryWrapper = QueryGenerator.initQueryWrapper(eaBusinessApplyChange, req.getParameterMap());
		if (StringUtils.isNotBlank(billDateBegin)){
			queryWrapper.ge("bill_date", billDateBegin);
		}
		if (StringUtils.isNotBlank(billDateEnd)){
			queryWrapper.le("bill_date", billDateEnd);
		}
		//add-begin-by wujinbiao for 添加查询条件 列表排序，创建人
		queryWrapper.orderByDesc("create_time");
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		queryWrapper.eq("create_by",loginUser.getId());
		//add-end-by wujinbiao for 添加查询条件

		Page<EaBusinessApplyChange> page = new Page<EaBusinessApplyChange>(pageNo, pageSize);
		IPage<EaBusinessApplyChange> pageList = eaBusinessApplyChangeService.page(page, queryWrapper);
		//add-begin-by wujinbiao for 返回申请人中文名称
		List<EaBusinessApplyChange> records = pageList.getRecords();
		for (EaBusinessApplyChange eaBusinessApplyChange1:records) {
			NcPersonnel ncPersonnel = ncPersonnelService.queryById(eaBusinessApplyChange1.getPersonId());
			if(ncPersonnel != null){
				eaBusinessApplyChange1.setPersonIdName(ncPersonnel.getName());
			}
		}
		//add-end-by wujinbiao for 返回申请人中文名称
		return Result.OK(pageList);
	}
	
	/**
 	 * @return
	 */
	@AutoLog(value = "出差申请变更单-添加")
	@ApiOperation(value="出差申请变更单-添加", notes="出差申请变更单-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody EaBusinessApplyChangePage eaBusinessApplyChangePage) {
		EaBusinessApplyChange eaBusinessApplyChange = new EaBusinessApplyChange();
		BeanUtils.copyProperties(eaBusinessApplyChangePage, eaBusinessApplyChange);
		eaBusinessApplyChange.setSaveType("add");
		eaBusinessApplyChangeService.saveMain(eaBusinessApplyChange, eaBusinessApplyChangePage.getEaBusinessPerDtlList());
		//add-begin-by 2022-02-07 wjb for 返回主表、子表数据给前端
		EaBusinessApplyChangePage eaBusinessApplyChangePage1 = new EaBusinessApplyChangePage();
		BeanUtils.copyProperties(eaBusinessApplyChange,eaBusinessApplyChangePage1);
		eaBusinessApplyChangePage1.setEaBusinessPerDtlList(eaBusinessApplyChangePage.getEaBusinessPerDtlList());
		//add-end-by 2022-02-07 wjb for 返回主表、子表数据给前端
		return Result.OK(eaBusinessApplyChangePage1);
	}
	
	/**
	 *  编辑
	 *
	 * @param eaBusinessApplyChangePage
	 * @return
	 */
	@AutoLog(value = "出差申请变更单-编辑")
	@ApiOperation(value="出差申请变更单-编辑", notes="出差申请变更单-编辑")
	@PostMapping(value = "/edit")
	public Result<?> edit(@RequestBody EaBusinessApplyChangePage eaBusinessApplyChangePage) {
		EaBusinessApplyChange eaBusinessApplyChange = new EaBusinessApplyChange();
		BeanUtils.copyProperties(eaBusinessApplyChangePage, eaBusinessApplyChange);
		EaBusinessApplyChange eaBusinessApplyChangeEntity = eaBusinessApplyChangeService.getById(eaBusinessApplyChange.getId());
		if(eaBusinessApplyChangeEntity==null) {
			return Result.error("未找到对应数据");
		}
		eaBusinessApplyChange.setSaveType("add");
		eaBusinessApplyChangeService.updateMain(eaBusinessApplyChange, eaBusinessApplyChangePage.getEaBusinessPerDtlList());
		//add-begin-by 2022-02-07 wjb for 返回主表、子表数据给前端
		EaBusinessApplyChangePage eaBusinessApplyChangePage1 = new EaBusinessApplyChangePage();
		BeanUtils.copyProperties(eaBusinessApplyChange,eaBusinessApplyChangePage1);
		eaBusinessApplyChangePage1.setEaBusinessPerDtlList(eaBusinessApplyChangePage.getEaBusinessPerDtlList());
		//add-end-by 2022-02-07 wjb for 返回主表、子表数据给前端
		return Result.OK(eaBusinessApplyChangePage1);
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "出差申请变更单-通过id删除")
	@ApiOperation(value="出差申请变更单-通过id删除", notes="出差申请变更单-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		eaBusinessApplyChangeService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "出差申请变更单-批量删除")
	@ApiOperation(value="出差申请变更单-批量删除", notes="出差申请变更单-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.eaBusinessApplyChangeService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="出差申请变更单-通过id查询", notes="出差申请变更单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		EaBusinessApplyChangePage eaBusinessApplyChangePage = new EaBusinessApplyChangePage();
		EaBusinessApplyChange eaBusinessApplyChange = eaBusinessApplyChangeService.getById(id);
		if(eaBusinessApplyChange==null) {
			return Result.error("未找到对应数据");
		}
		if (StringUtils.isNotBlank(eaBusinessApplyChange.getPersonId())){
			NcPersonnel ncPersonnel = ncPersonnelService.queryById(eaBusinessApplyChange.getPersonId());
			eaBusinessApplyChange.setPersonIdName(ncPersonnel.getName());
		}
		BeanUtils.copyProperties(eaBusinessApplyChange,eaBusinessApplyChangePage);
		//添加出行人明细
		List<EaBusinessPerDtl> eaBusinessPerDtlList = eaBusinessPerDtlService.selectByMainId(id);
		//add-begin-by wjb for 循环遍历返回出行人中文
		if(eaBusinessPerDtlList.size()>0){
			for (EaBusinessPerDtl eaBusinessPerDtl:eaBusinessPerDtlList) {
				if (StringUtils.isNotBlank(eaBusinessPerDtl.getPersonnel())){
					NcPersonnel ncPersonnel = ncPersonnelService.queryById(eaBusinessPerDtl.getPersonnel());
					if(ncPersonnel != null){
						eaBusinessPerDtl.setPersonnelName(ncPersonnel.getName());
					}
				}
			}
		}
		//add-end-by wjb for 循环遍历返回出行人中文
		eaBusinessApplyChangePage.setEaBusinessPerDtlList(eaBusinessPerDtlList);
		return Result.OK(eaBusinessApplyChangePage);
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="出行人明细-主表ID查询", notes="出行人明细-通主表ID查询")
	@GetMapping(value = "/queryEaBusinessPerDtlByMainId")
	public Result<?> queryEaBusinessPerDtlListByMainId(@RequestParam(name="id",required=true) String id) {
		List<EaBusinessPerDtl> eaBusinessPerDtlList = eaBusinessPerDtlService.selectByMainId(id);
		return Result.OK(eaBusinessPerDtlList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param eaBusinessApplyChange
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, EaBusinessApplyChange eaBusinessApplyChange) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<EaBusinessApplyChange> queryWrapper = QueryGenerator.initQueryWrapper(eaBusinessApplyChange, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<EaBusinessApplyChange> queryList = eaBusinessApplyChangeService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<EaBusinessApplyChange> eaBusinessApplyChangeList = new ArrayList<EaBusinessApplyChange>();
      if(oConvertUtils.isEmpty(selections)) {
          eaBusinessApplyChangeList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          eaBusinessApplyChangeList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<EaBusinessApplyChangePage> pageList = new ArrayList<EaBusinessApplyChangePage>();
      for (EaBusinessApplyChange main : eaBusinessApplyChangeList) {
          EaBusinessApplyChangePage vo = new EaBusinessApplyChangePage();
          BeanUtils.copyProperties(main, vo);
          List<EaBusinessPerDtl> eaBusinessPerDtlList = eaBusinessPerDtlService.selectByMainId(main.getId());
          vo.setEaBusinessPerDtlList(eaBusinessPerDtlList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "ea_business_apply_change列表");
      mv.addObject(NormalExcelConstants.CLASS, EaBusinessApplyChangePage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("ea_business_apply_change数据", "导出人:"+sysUser.getRealname(), "ea_business_apply_change"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<EaBusinessApplyChangePage> list = ExcelImportUtil.importExcel(file.getInputStream(), EaBusinessApplyChangePage.class, params);
              for (EaBusinessApplyChangePage page : list) {
                  EaBusinessApplyChange po = new EaBusinessApplyChange();
                  BeanUtils.copyProperties(page, po);
                  eaBusinessApplyChangeService.saveMain(po, page.getEaBusinessPerDtlList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
